import {addIncomingOrdersApi} from '@/api/warehouse'
import {resetForm} from "@/utils/common";

export default {
  data() {
    return {
      state: -1, // -1入库
      isAutoSubmit: false,
      isAutoLoading: false,
      timer: null,
      form: {
        orders: ''
      },
      rules: {
        orders: {required: true, message: '请输入单号', trigger: 'blur'}
      }
    }
  },
  watch: {
    'form.orders'(value) {
      if (value[value.length - 1] === '\n') {
        this.loadSound();
      }
    }
  },
  mounted() {
    // 持久化
    if (this.$storeGet.operation.includes(this.state)) {
      this.isAutoSubmit = true
      this.changeAuto(true)
    }
  },
  beforeDestroy() {
    this.resetAuto()
  },
  methods: {
    /**
     * @description 自动上传
     * */
    // 拼接错误单号
    joint(numbers) {
      if (!numbers) return
      if (typeof numbers === 'string') {
        numbers = numbers.split(',')
      }
      let length = this.form.orders.length
      let last = this.form.orders[length - 1]
      if (last === '\n' || last === undefined) {
        this.form.orders += numbers.join('\n') + '\n'
      } else {
        this.form.orders += '\n' + numbers.join('\n') + '\n'
      }
    },
    // 自动上传状态变化
    changeAuto(value) {
      if (value) {
        this.auto()
        this.$storeSet('addOperation', this.state)
      } else {
        this.resetAuto()
        this.$storeSet('delOperation', this.state)
      }
    },
    // 发生错误
    goWrong(list) {
      this.$errorNotify('上传期间发生错误，终止自动上传')
      this.resetAuto()
      this.joint(list)
      this.$storeSet('delOperation', this.state)
    },
    // 重置自动上传
    resetAuto() {
      this.isAutoSubmit = false
      this.isAutoLoading = false
      clearInterval(this.timer)
    },
    auto() {
      this.timer = setInterval(() => {
        if (!this.isAutoSubmit) return
        if (this.isAutoLoading) return

        let value = this.form.orders
        value = value.trim(); // 去空
        if (!value) return;
        this.form.orders = ''
        let numbers = this.getString(value)
        // 上传
        this.isAutoLoading = true
        addIncomingOrdersApi({numbers}).then(result => {
          if (result.status !== 200) {
            this.goWrong(value.split(','))
            return
          }
          this.isAutoLoading = false
        }).catch(() => {
          this.goWrong(value.split(','))
        })
      }, 10000)
    },
    /**
     * */

    // 手动提交
    submit() {
      let value = this.form.orders.trim();
      if (!value) {
        this.$errorMsg('请输入单号')
        return
      }
      let param = {
        numbers: this.getString(value)
      };
      this.$startLoading();
      addIncomingOrdersApi(param).then(result => {
        this.$stopLoading()
        if (result.status !== 200) return
        this.cancel();
      }).catch(() => {
        this.$stopLoading()
      })
    },

    // 关闭
    cancel() {
      resetForm(this, 'form')
    },

    // 获得单号字符串
    getString(value) {
      let list = [];
      value = value.split('\n');
      value.forEach(item => { // 去空格
        item = item.trim();
        if (item !== '') list.push(item)
      });
      for (let i = 0; i < list.length; i++) { // 去重
        for (let j = i + 1; j < list.length; j++) {
          if (list[i] === list[j]) {
            list.splice(j, 1);
            j--;
          }
        }
      }
      return list.join(',')
    },

    // 回车提示音
    loadSound() {
      let con = new AudioContext();
      let req = new XMLHttpRequest();
      req.open('GET', '/assets/tips.mp3', true);
      req.responseType = 'arraybuffer';
      req.onload = function () {
        con.decodeAudioData(req.response, function (buffer) {
          let source = con.createBufferSource();
          source.buffer = buffer;
          source.connect(con.destination);
          source.start(0);
        }, function (e) {
          console.info(e);
        });
      };
      req.send();
    }
  }
}
